package net.j4love.mybatis.plugin;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.Properties;

/**
 * @author he peng
 * @create 2017/11/8 15:24
 * @see
 */

@Intercepts({
        @Signature(
                type = Executor.class,
                method = "query",
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
        ),
})
public class MyInterceptor implements Interceptor {

    private static final Logger LOG = LoggerFactory.getLogger(MyInterceptor.class);

    /**
     * 对指定类的指定方法进行拦截 , {@link Intercepts} ,  {@link Signature}
     * @param invocation
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        LOG.debug("MyInterceptor #intercept run");
        return invokeTargetMethod(invocation);
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target,this);
        }
        return target;
    }

    @Override
    public void setProperties(Properties properties) {
        System.out.println("net.j4love.mybatis.plugin.MyInterceptor");
    }

    private Object invokeTargetMethod(Invocation invocation) throws Exception {
        Method method = invocation.getMethod();
        if (! method.isAccessible()) {
            method.setAccessible(true);
        }
        return method.invoke(invocation.getTarget(),invocation.getArgs());
    }
}
